package com.goti.nettyClient.Dispatcher;

import com.goti.nettyClient.protobuf.MsgPro;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @program: netty_client
 * @package: com.goti.netty_client.Dispatcher
 * @description: netty客戶端調度器
 * @author: goti
 * @create: 2019-11-26 11:19
 */
@Component
public class NettyClientDispatcher {
    private static ChannelHandlerContext ctx;



    public void setChannelHandlerContext(ChannelHandlerContext ctx){
        this.ctx=ctx;
    }

    public ChannelHandlerContext getChannelHandlerContext(){
        return ctx;
    }

    public void removeCtx(){
        try {
            if (ctx!=null){
                ctx.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ctx=null;
        }
    }

    /**
     * 發送消息
     * @return
     */
    public boolean sendMsg(MsgPro.UserMsg msg){
        if (ctx!=null){
            ChannelFuture ch=ctx.writeAndFlush(msg);
            return ch.isSuccess();
        }else {
            return false;
        }

    }
    public boolean sendMsg(String proCode, String methodType, String version, String message){
        System.out.println(new Date().getTime());

        if (ctx!=null){
            ChannelFuture ch=ctx.writeAndFlush(getMsg(proCode,methodType,version,message));
            return ch.isSuccess();
        }else {
            return false;
        }
    }

    private MsgPro.UserMsg getMsg(String proCode, String methodType, String version, String message){
        MsgPro.UserMsg msg= MsgPro
                .UserMsg
                .newBuilder()
                .setMsg(message)
                .setProCode(proCode)
                .setMethodType(methodType)
                .setVersion(version)
                .build();
        return msg;
    }

}
